import React, { PureComponent } from 'react'
import gotop from '@/assets/images/gotop.png'
import css from './index.module.scss'
export default class GoTop extends PureComponent {

    state = {
        activeClass: ''
    }

    handleTop = () => {
        const doc = document.scrollingElement
        Math.easeout(doc.scrollTop, 0, 4, function (value) {
            doc.scrollTop = value
        })
    }
    
    scrollFn = () => {
        // A 起始位置 B目标位置 rate缓动速率
        Math.easeout = function (A, B, rate, callback) {
            if (A === B || typeof A !== 'number') {
                return  
            }
            B = B || 0
            rate = rate || 2
            
            const step = function () {
                A = A + (B - A) / rate
                
                if (A < 1) {
                    callback(B, true)
                    return
                }
                callback(A, false)
                requestAnimationFrame(step)   
            }
            step()
        }
    }

    listenScroll = e => {
        const st = document.scrollingElement.scrollTop
        const cls = st > 200 ? 'active' : ''
        this.setState({
            activeClass: cls
        })
    }

    componentDidMount() {
        this.scrollFn()
        window.addEventListener('scroll', this.listenScroll)
    }

    componentWillUnmount() {
        window.removeEventListener('scroll', this.listenScroll)
    }

    render() {
        const { activeClass } = this.state
        return (
            <div className={`${css['wrap']} ${activeClass ? css[activeClass] : ''}`} onClick={this.handleTop}>
                <img className={css['img']} src={gotop} alt="返回顶部" />
            </div>
        )
    }
}
